// 导入 wechat-validate 模块
import validate from 'wechat-validate'
// 获取应用实例
const app = getApp()

Page({
  behaviors: [validate],
  data: {
    countDownVisible: false,
    mobile: '',
    code: '',
    timeData: {},
  },
  onLoad({ redirectURL }) {
    // 获取跳转路径
    this.redirectURL = redirectURL
  },
  // wxValidate 提供了属性，用来定义验证规则
  rules: {
    mobile: [
      {
        required: true,
        message: '请填写手机号码!',
      },
      {
        pattern: /^1[3-8]\d{9}$/,
        message: '请检查手机号码是否正确!',
      },
    ],
    code: [
      {
        required: true,
        message: '请填写验证码!',
      },
      {
        pattern: /^\d{6}$/,
        message: '请检查验证码格式是否正确!',
      },
    ],
  },
  // 监听时间的变化
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes > 1 || ev.detail.seconds > 0,
    })
  },
  // 获取短信验证码
  async getSMSCode() {
    // this.validate
    const { valid, message } = this.validate('mobile')
    if (!valid) {
      wx.utils.toast(message)
      return
    }
    this.setData({
      countDownVisible: true,
    })
    // 调用登录接口
    try {
      const res = await wx.http.get('/code', {
        mobile: this.data.mobile,
      })
      this.setData({
        code: res.data.code,
      })
      // 检验验证码是否发送成功
      if (res.code !== 10000) {
        wx.toast('验证码获取失败')
      }
    } catch (error) {
      console.log(error, 'error')
    }
  },
  // 提交表单数据，完成登录/注册的功能
  async submitForm() {
    // 验证数据是否合法
    if (!this.validate()) return
  },
})
